package com.xueyi.system.company.controller;

import com.xueyi.common.core.constant.basic.SecurityConstants;
import com.xueyi.common.core.context.SecurityContextHolder;
import com.xueyi.common.core.exception.ServiceException;
import com.xueyi.common.core.utils.StringUtils;
import com.xueyi.common.core.utils.file.FileTypeUtils;
import com.xueyi.common.core.utils.file.MimeTypeUtils;
import com.xueyi.common.core.web.result.R;
import com.xueyi.common.security.service.TokenService;
import com.xueyi.common.security.utils.SecurityUtils;
import com.xueyi.common.security.utils.SourceUtils;
import com.xueyi.file.api.domain.SysFile;
import com.xueyi.file.api.feign.RemoteFileService;
import com.xueyi.system.api.model.LoginUser;
import com.xueyi.system.api.source.domain.Source;
import com.xueyi.system.area.domain.dto.BaseAreaDto;
import com.xueyi.system.area.domain.query.BaseAreaQuery;
import com.xueyi.system.area.service.IBaseAreaService;
import com.xueyi.system.company.domain.query.CompanyQuery;
import com.xueyi.system.company.domain.dto.CompanyDto;
import com.xueyi.system.company.service.ICompanyService;
import com.xueyi.common.web.entity.controller.BaseController;
import com.xueyi.system.organize.service.ISysUserService;
import com.xueyi.system.parcel.domain.dto.BaseParcelDto;
import com.xueyi.system.parcel.domain.query.BaseParcelQuery;
import com.xueyi.system.parcel.service.IBaseParcelService;
import com.xueyi.tenant.api.tenant.domain.dto.TeTenantDto;
import com.xueyi.tenant.api.tenant.domain.po.TeTenantPo;
import com.xueyi.tenant.api.tenant.feign.RemoteTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xueyi.common.security.annotation.Logical;
import com.xueyi.common.security.annotation.RequiresPermissions;
import com.xueyi.common.core.web.validate.V_A;
import com.xueyi.common.core.web.validate.V_E;
import com.xueyi.common.core.web.result.AjaxResult;
import com.xueyi.common.log.annotation.Log;
import com.xueyi.common.log.enums.BusinessType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * 企业基础信息管理管理 业务处理
 *
 * @author yanhe
 */
@RestController
@RequestMapping("/company")
public class CompanyController extends BaseController<CompanyQuery, CompanyDto, ICompanyService> {



    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private RemoteTenantService remoteTenantService;

    @Autowired
    private IBaseAreaService baseAreaService;

    @Autowired
    private IBaseParcelService baseParcelService;

    /** 定义节点名称 */
    @Override
    protected String getNodeName() {
        return "企业基础信息管理" ;
    }

    /**
     * 查询企业基础信息管理列表
     */
    @Override
    @GetMapping("/list")
    @RequiresPermissions(Auth.COMPANY_LIST)
    public AjaxResult list(CompanyQuery company) {
        return super.list(company);
    }

    /**
     * 查询企业基础信息管理详细
     */
    @Override
    @GetMapping(value = "/{id}")
    @RequiresPermissions(Auth.COMPANY_SINGLE)
    public AjaxResult getInfoExtra(@PathVariable Serializable id) {
        return super.getInfoExtra(id);
    }

    /**
     * 企业基础信息管理导出
     */
    @Override
    @PostMapping("/export")
    @RequiresPermissions(Auth.COMPANY_EXPORT)
    @Log(title = "企业基础信息管理管理", businessType = BusinessType.EXPORT)
    public void export(HttpServletResponse response, CompanyQuery company) {
        super.export(response, company);
    }

    /**
     * 企业基础信息管理新增
     */
    @Override
    @PostMapping
    @RequiresPermissions(Auth.COMPANY_ADD)
    @Log(title = "企业基础信息管理管理", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated({V_A.class}) @RequestBody CompanyDto company) {
        return super.add(company);
    }

    /**
     * 企业基础信息管理修改
     */
    @Override
    @PutMapping
    @RequiresPermissions(Auth.COMPANY_EDIT)
    @Log(title = "企业基础信息管理管理", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated({V_E.class}) @RequestBody CompanyDto company) {
        return super.edit(company);
    }

    /**
     * 企业基础信息管理修改状态
     */
    @Override
    @PutMapping("/status")
    @RequiresPermissions(value = {Auth.COMPANY_EDIT, Auth.COMPANY_ES}, logical = Logical.OR)
    @Log(title = "企业基础信息管理管理", businessType = BusinessType.UPDATE_STATUS)
    public AjaxResult editStatus(@RequestBody CompanyDto company) {
        return super.editStatus(company);
    }

    /**
     * 企业基础信息管理批量删除
     */
    @Override
    @DeleteMapping("/batch/{idList}")
    @RequiresPermissions(Auth.COMPANY_DEL)
    @Log(title = "企业基础信息管理管理", businessType = BusinessType.DELETE)
    public AjaxResult batchRemove(@PathVariable List<Long> idList) {
        return super.batchRemove(idList);
    }


    /**
     * 获取当前企业信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        CompanyQuery companyQuery = new CompanyQuery();
        List<CompanyDto> companyDtoList = super.baseService.selectList(companyQuery);
        if(companyDtoList.size() > 1){
            return AjaxResult.error("系统异常出现多个企业信息");
        }
        return AjaxResult.success(companyDtoList.get(0));
    }


    /**
     * 企业logo上传
     */
    @PostMapping("/avatar")
    @Log(title = "企业信息管理 - 修改头像", businessType = BusinessType.UPDATE)
    public AjaxResult editAvatar(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            CompanyQuery companyQuery = new CompanyQuery();
            List<CompanyDto> companyDtoList = super.baseService.selectList(companyQuery);
            CompanyDto companyDto1 = companyDtoList.get(0);
            String extension = FileTypeUtils.getExtension(file);
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return AjaxResult.error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            R<SysFile> fileResult = remoteFileService.upload(file);
            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData()))
                return AjaxResult.error("文件服务异常，请联系管理员！");
            String url = fileResult.getData().getUrl();
            CompanyDto companyDto = companyService.selectById(companyDto1.getId());
            if (companyService.updateUserAvatar(companyDto1.getId(), url) > 0) {
                String oldAvatarUrl = companyDto.getLogo();
                if (StringUtils.isNotEmpty(oldAvatarUrl)) {
                    remoteFileService.delete(oldAvatarUrl);
                }
                AjaxResult ajax = AjaxResult.success();
                ajax.put(AjaxResult.URL_TAG, url);
               /* // 更新缓存 - 用户头像
                loginUser.getUser().setAvatar(url);
                tokenService.setLoginUser(loginUser);*/
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员！");
    }

    /**
     * 查询企业基础信息管理列表
     */
    @GetMapping("/getCompanyList")
    public AjaxResult getCompanyList(CompanyQuery company) {
        List list = new ArrayList<>();
        R<List<TeTenantDto>> tenantResult = remoteTenantService.getTenantList(SecurityConstants.INNER);
        if (tenantResult.isFail()) {
            throw new ServiceException("当前访问人数过多，请稍后再试！");
        }
        Source source = SourceUtils.getSourceCache("1587983403190247425");
        SecurityContextHolder.setSourceName(source.getMaster());
        List<TeTenantDto> tenantPoList = tenantResult.getData();
        Integer count = 0;
        BigDecimal num = new BigDecimal("0");
        Integer parcelNum = 0;
        List<CompanyDto> companyDtoList;
        for (TeTenantDto teTenantDto : tenantPoList) {
            SecurityContextHolder.setEnterpriseId(teTenantDto.getId() + "");
            companyDtoList = companyService.selectList(company);
            BaseAreaQuery baseAreaQuery = new BaseAreaQuery();
            List<BaseAreaDto> areaDtoList = baseAreaService.selectList(baseAreaQuery);
            if(areaDtoList.size() > 0){
                count = areaDtoList.size();
                for (BaseAreaDto baseAreaDto : areaDtoList) {
                   num=num.add(baseAreaDto.getArea());
                }
            }
            BaseParcelQuery baseParcelQuery = new BaseParcelQuery();
            List<BaseParcelDto> parcelDtoList = baseParcelService.selectList(baseParcelQuery);
            if(parcelDtoList.size() > 0){
                parcelNum = parcelDtoList.size();
            }
            Map map = new HashMap<>();
            if(companyDtoList.size()>0){
                map.put("companyInfo",companyDtoList);
                map.put("count",count);
                map.put("num",num);
                map.put("parcelNum",parcelNum);
                map.put("enterpriseName",teTenantDto.getName());
                map.put("enterpriseId",teTenantDto.getId());
                list.add(map);
            }
        }
        return AjaxResult.success(list);
    }


    /**
     * 获取企业基础信息管理选择框列表
     */
    @Override
    @GetMapping("/option")
    public AjaxResult option() {
        return super.option();
    }

    interface Auth {
        /** 系统 - 企业基础信息管理管理 - 列表 */
        String COMPANY_LIST = "system:company:list" ;
        /** 系统 - 企业基础信息管理管理 - 详情 */
        String COMPANY_SINGLE = "system:company:single" ;
        /** 系统 - 企业基础信息管理管理 - 新增 */
        String COMPANY_ADD = "system:company:add" ;
        /** 系统 - 企业基础信息管理管理 - 修改 */
        String COMPANY_EDIT = "system:company:edit" ;
        /** 系统 - 企业基础信息管理管理 - 修改状态 */
        String COMPANY_ES = "system:company:es" ;
        /** 系统 - 企业基础信息管理管理 - 删除 */
        String COMPANY_DEL = "system:company:delete" ;
        /** 系统 - 企业基础信息管理管理 - 导出 */
        String COMPANY_EXPORT = "system:company:export" ;
    }
}
